/*
 * @Author: ZhaoZhiqi
 * @Date: 2022-10-19 14:50:20
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2022-12-13 14:44:38
 * @Description: 项目帮代办
 * @FilePath: \tuanfeng-admin-front\src\pages\Agency\useForm.ts
 */
import { ref, reactive, onMounted } from 'vue'
import {
    replyFirmAgentAPI,
    getAcceptDeptAPI
} from "../../api/feedback";
import { ElMessage } from 'element-plus';

/**
 * @description: 新增/编辑表单
 * @param {Function} query 查询列表方法
 * @return {*}
 */
export default function useForm(query: Function) {
    // 表单相关
    const dialogVisible = ref(false);
    const formRef = ref();
    const isEdit = ref(false);
    const deptsList = ref([]);
    const form = reactive({
        id: '',
        acceptDeptName: '',
        reply: '',
    })

    onMounted(() => {
        getAcceptDeptAPI().then(res => {
            deptsList.value = res.data;
        })
    })

    // 新增/编辑 操作
    const handleEdit = (item: any) => {
        // 编辑回填
        if (item) {
            isEdit.value = true;
            form.id = item.id
            form.acceptDeptName = item.acceptDeptName
            form.reply = item.reply
        }
        // 新增清空
        else {
            isEdit.value = false;
            form.id = ""
            form.acceptDeptName = ""
            form.reply = ""
        }

        dialogVisible.value = true;
    };

    // 确定 新增/编辑 操作
    const handleConfirm = () => {
        formRef.value.validate((valid: any, fields: any) => {
            if (valid) {
                replyFirmAgentAPI({ ...form }).then(res => {
                    if (res.code === 200) {
                        ElMessage({
                            message: '回复成功',
                            type: 'success',
                        })
                    }
                    dialogVisible.value = false;
                    query();
                })
            } else {
                console.log('error submit!', fields)
            }
        })
    }

    return {
        dialogVisible,
        formRef,
        isEdit,
        form,
        deptsList,
        handleEdit,
        handleConfirm,
    }
}